<?php
/**
 * [DB模型]
 * 
 * @version $Id: Exchange.php 277 2012-04-24 08:37:00Z linsir123 $
 */
class dbExchange extends ActiveRelation 
{
	/**
	 * @var 数据库表名
	 */
	public $table = 'exchange';
	
	/**
	 * 取得列表
	 */
	public function getList($start, $offset, $params = array())
	{
		$this->_searchSql($params);
		
		///
		$this->limit($start, $offset);
		return $this->getResults();
	}
	
	/**
	 * 取得总数
	 */
	public function getListCount($params = array())
	{
		$this->_searchSql($params);
		
		///
		return $this->getCount();
	}
	
	/**
	 * 构造查询SQL
	 */
	private function _searchSql($params)
	{
		if ( ! empty($params['uid'])) 
			$this->where('uid', $params['uid']);
	}
	
	/**
	 * 取得列表
	 */
	public function getListWithAccount($start, $offset, $params = array())
	{
		$this->_searchSqlWithAccount($params);
		
		///
		$this->limit($start, $offset);
		return $this->getResults();
	}
	
	/**
	 * 取得总数
	 */
	public function getListCountWithAccount($params = array())
	{
		$this->_searchSqlWithAccount($params);
		
		///
		return $this->getCount();
	}
	
	/**
	 * 构造查询SQL
	 */
	private function _searchSqlWithAccount($params)
	{
		$db = D::account();
		$db->field('balance');
		
		///
		if ( ! empty($params['uid'])) 
			$this->where('uid', $params['uid']);
			
		if (isset($params['state'])) 
			$this->where('state', $params['state']);
			
		///
		$this->joinLeft($db, 'uid', 'uid');
	}
	
	/**
	 * 支付返现费用
	 * // 场景：支付用户的返现的时候
	 */
	public function pay($id, $description)
	{
		return $this->updateById($id, array(
			'description' => $description,
			'pay_time' => time(),
			'state' => 1,
		));
	}
	
	/**
	 * 已提现次数
	 */
	public function getPayTimesByUser($uId)
	{
		return $this->where(array('uid'=>$uId, 'state'=>1))->getCount();
	}
	
	/**
	 * 已提现金额
	 */
	public function getPayMoneysByUser($uId)
	{
		return $this->where(array('uid'=>$uId, 'state'=>1))->getSum('money');
	}
}
